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