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