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