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