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