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