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