better win detection
[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         my $lockfn = "$root/perl/cluster.lock";       # 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
41 use Msg;
42 use IntMsg;
43 use ExtMsg;
44 use AGWMsg;
45 use DXVars;
46 use DXDebug;
47 use DXLog;
48 use DXLogPrint;
49 use DXUtil;
50 use DXChannel;
51 use DXUser;
52 use DXM;
53 use DXCommandmode;
54 use DXProt;
55 use DXMsg;
56 use DXCluster;
57 use DXCron;
58 use DXConnect;
59 use Prefix;
60 use Bands;
61 use Geomag;
62 use CmdAlias;
63 use Filter;
64 use DXDb;
65 use AnnTalk;
66 use WCY;
67 use DXDupe;
68 use BadWords;
69
70 use Data::Dumper;
71 use IO::File;
72 use Fcntl ':flock'; 
73 use POSIX ":sys_wait_h";
74
75 use Local;
76
77 package main;
78
79 use strict;
80 use vars qw(@inqueue $systime $version $starttime $lockfn @outstanding_connects 
81                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr 
82                         $clusterport $mycall $decease $build $is_win
83                    );
84
85 @inqueue = ();                                  # the main input queue, an array of hashes
86 $systime = 0;                                   # the time now (in seconds)
87 $version = "1.47";                              # the version no of the software
88 $starttime = 0;                 # the starting time of the cluster   
89 $lockfn = "cluster.lock";       # lock file name
90 #@outstanding_connects = ();     # list of outstanding connects
91 @listeners = ();                                # list of listeners
92 $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
93
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         Msg->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 #
308 # The start of the main line of code 
309 #
310 #############################################################
311
312 $starttime = $systime = time;
313 $lang = 'en' unless $lang;
314
315 # open the debug file, set various FHs to be unbuffered
316 dbginit();
317 foreach (@debug) {
318         dbgadd($_);
319 }
320 STDOUT->autoflush(1);
321
322 # calculate build number
323 $build = $main::version;
324
325 if (opendir(DIR, "$main::root/perl")) {
326         my @d = readdir(DIR);
327         closedir(DIR);
328         foreach my $fn (@d) {
329                 if ($fn =~ /^cluster\.pl$/ || $fn =~ /\.pm$/) {
330                         my $f = new IO::File "$main::root/perl/$fn" or next;
331                         while (<$f>) {
332                                 if (/^#\s+\$Id:\s+[\w\._]+,v\s+(\d+\.\d+)/ ) {
333                                         $build += $1;
334                                         last;
335                                 }
336                         }
337                         $f->close;
338                 }
339         }
340 }
341
342 Log('cluster', "DXSpider V$version, build $build started");
343
344 # banner
345 dbg('err', "DXSpider Version $version, build $build started", "Copyright (c) 1998-2001 Dirk Koopman G1TLH");
346
347 # load Prefixes
348 dbg('err', "loading prefixes ...");
349 Prefix::load();
350
351 # load band data
352 dbg('err', "loading band data ...");
353 Bands::load();
354
355 # initialise User file system
356 dbg('err', "loading user file system ..."); 
357 DXUser->init($userfn, 1);
358
359 # start listening for incoming messages/connects
360 use Listeners;
361
362 dbg('err', "starting listeners ...");
363 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
364 $conn->conns("Server $clusteraddr/$clusterport");
365 push @listeners, $conn;
366 dbg('err', "Internal port: $clusteraddr $clusterport");
367 for (@main::listen) {
368         $conn = ExtMsg->new_server($_->[0], $_->[1], \&login);
369         $conn->conns("Server $_->[0]/$_->[1]");
370         push @listeners, $conn;
371         dbg('err', "External Port: $_->[0] $_->[1]");
372 }
373 AGWMsg::init(\&new_channel);
374
375 # load bad words
376 dbg('err', "load badwords: " . (BadWords::load or "Ok"));
377
378 # prime some signals
379 unless ($is_win) {
380         unless ($DB::VERSION) {
381                 $SIG{INT} = \&cease;
382                 $SIG{TERM} = \&cease;
383         }
384         $SIG{HUP} = 'IGNORE';
385         $SIG{CHLD} = sub { $zombies++ };
386         
387         $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
388         $SIG{IO} = sub {        dbg('err', "SIGIO received"); };
389         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
390         $SIG{KILL} = 'DEFAULT';     # as if it matters....
391
392         # catch the rest with a hopeful message
393         for (keys %SIG) {
394                 if (!$SIG{$_}) {
395                         #               dbg('chan', "Catching SIG $_");
396                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
397                 }
398         }
399 }
400
401 # start dupe system
402 DXDupe::init();
403
404 # read in system messages
405 DXM->init();
406
407 # read in command aliases
408 CmdAlias->init();
409
410 # initialise the Geomagnetic data engine
411 Geomag->init();
412 WCY->init();
413
414 # initial the Spot stuff
415 Spot->init();
416
417 # initialise the protocol engine
418 dbg('err', "reading in duplicate spot and WWV info ...");
419 DXProt->init();
420
421 # put in a DXCluster node for us here so we can add users and take them away
422 DXNode->new($DXProt::me, $mycall, 0, 1, $DXProt::myprot_version); 
423
424 # read in any existing message headers and clean out old crap
425 dbg('err', "reading existing message headers ...");
426 DXMsg->init();
427 DXMsg::clean_old();
428
429 # read in any cron jobs
430 dbg('err', "reading cron jobs ...");
431 DXCron->init();
432
433 # read in database descriptors
434 dbg('err', "reading database descriptors ...");
435 DXDb::load();
436
437 # starting local stuff
438 dbg('err', "doing local initialisation ...");
439 eval {
440         Local::init();
441 };
442 dbg('local', "Local::init error $@") if $@;
443
444 # print various flags
445 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
446
447 # this, such as it is, is the main loop!
448 dbg('err', "orft we jolly well go ...");
449
450 #open(DB::OUT, "|tee /tmp/aa");
451
452 for (;;) {
453 #       $DB::trace = 1;
454         
455         Msg->event_loop(10, 0.010);
456         my $timenow = time;
457         process_inqueue();                      # read in lines from the input queue and despatch them
458 #       $DB::trace = 0;
459         
460         # do timed stuff, ongoing processing happens one a second
461         if ($timenow != $systime) {
462                 reap if $zombies;
463                 $systime = $timenow;
464                 DXCron::process();      # do cron jobs
465                 DXCommandmode::process(); # process ongoing command mode stuff
466                 DXProt::process();              # process ongoing ak1a pcxx stuff
467                 DXConnect::process();
468                 DXMsg::process();
469                 DXDb::process();
470                 DXUser::process();
471                 DXDupe::process();
472                 AGWMsg::process();
473                                 
474                 eval { 
475                         Local::process();       # do any localised processing
476                 };
477                 dbg('local', "Local::process error $@") if $@;
478         }
479         if ($decease) {
480                 last if --$decease <= 0;
481         }
482 }
483 cease(0);
484 exit(0);
485
486