2c94dcc1cb619571baef325fe4607071c453bb1c
[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 use Msg;
42 use IntMsg;
43 use ExtMsg;
44 use DXVars;
45 use DXDebug;
46 use DXLog;
47 use DXLogPrint;
48 use DXUtil;
49 use DXChannel;
50 use DXUser;
51 use DXM;
52 use DXCommandmode;
53 use DXProt;
54 use DXMsg;
55 use DXCluster;
56 use DXCron;
57 use DXConnect;
58 use Prefix;
59 use Bands;
60 use Geomag;
61 use CmdAlias;
62 use Filter;
63 use DXDb;
64 use AnnTalk;
65 use WCY;
66 use DXDupe;
67 use BadWords;
68
69 use Data::Dumper;
70 use Fcntl ':flock'; 
71 use POSIX ":sys_wait_h";
72
73 use Local;
74
75 package main;
76
77 #use strict;
78 #use vars qw(@inqueue $systime $version $starttime $lockfn @outstanding_connects $zombies $root
79 #                  $lang $myalias @debug $userfn $clusteraddr $clusterport $mycall $decease );
80
81 @inqueue = ();                                  # the main input queue, an array of hashes
82 $systime = 0;                                   # the time now (in seconds)
83 $version = "1.47";                              # the version no of the software
84 $starttime = 0;                 # the starting time of the cluster   
85 $lockfn = "cluster.lock";       # lock file name
86 #@outstanding_connects = ();     # list of outstanding connects
87 @listeners = ();                                # list of listeners
88
89       
90 # send a message to call on conn and disconnect
91 sub already_conn
92 {
93         my ($conn, $call, $mess) = @_;
94         
95         dbg('chan', "-> D $call $mess\n"); 
96         $conn->send_now("D$call|$mess");
97         sleep(1);
98         dbg('chan', "-> Z $call bye\n");
99         $conn->send_now("Z$call|bye"); # this will cause 'client' to disconnect
100         sleep(1);
101         $conn->disconnect;
102 }
103
104 # handle incoming messages
105 sub rec
106 {
107         my ($conn, $msg, $err) = @_;
108         my $dxchan = DXChannel->get_by_cnum($conn); # get the dxconnnect object for this message
109         
110         if (!defined $msg || (defined $err && $err)) {
111                 if ($dxchan) {
112                         if (defined $err) {
113                                 $conn->disconnect;
114                                 undef $conn;
115                                 $dxchan->conn(undef);
116                         }
117                         $dxchan->disconnect;
118                 } elsif ($conn) {
119                         $conn->disconnect;
120                 }
121                 return;
122         }
123         
124         # set up the basic channel info - this needs a bit more thought - there is duplication here
125         if (!defined $dxchan) {
126                 my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
127                 return unless defined $sort;
128  
129                 # is there one already connected to me - locally? 
130                 my $user = DXUser->get($call);
131                 if ($sort ne 'O' && Msg->conns($call)) {
132                         my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call, $main::mycall);
133                         already_conn($conn, $call, $mess);
134                         return;
135                 }
136                 
137                 # is there one already connected elsewhere in the cluster?
138                 if ($user) {
139                         if (($user->is_node || $call eq $myalias) && !DXCluster->get_exact($call)) {
140                                 ;
141                         } else {
142                                 if (my $ref = DXCluster->get_exact($call)) {
143                                         my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->call);
144                                         already_conn($conn, $call, $mess);
145                                         return;
146                                 }
147                         }
148                         $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
149                 } else {
150                         if (my $ref = DXCluster->get_exact($call)) {
151                                 my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->call);
152                                 already_conn($conn, $call, $mess);
153                                 return;
154                         }
155                         $user = DXUser->new($call);
156                 }
157
158                 # is he locked out ?
159                 if ($user->lockout) {
160                         Log('DXCommand', "$call is locked out, disconnected");
161                         $conn->send_now("Z$call|bye"); # this will cause 'client' to disconnect
162                         $conn->disconnect;
163                         return;
164                 }
165
166                 # mark him up
167                 $conn->conns($call) unless $sort eq 'O';
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         
176         # queue the message and the channel object for later processing
177         if (defined $msg) {
178                 my $self = bless {}, "inqueue";
179                 $self->{dxchan} = $dxchan;
180                 $self->{data} = $msg;
181                 push @inqueue, $self;
182         }
183 }
184
185 sub login
186 {
187         return \&rec;
188 }
189
190 # cease running this program, close down all the connections nicely
191 sub cease
192 {
193         my $dxchan;
194
195         $SIG{'TERM'} = 'IGNORE';
196         $SIG{'INT'} = 'IGNORE';
197         
198         DXUser::sync;
199
200         eval {
201                 Local::finish();   # end local processing
202         };
203         dbg('local', "Local::finish error $@") if $@;
204
205         # disconnect nodes
206         foreach $dxchan (DXChannel->get_all()) {
207                 next unless $dxchan->is_node;
208             $dxchan->disconnect unless $dxchan == $DXProt::me;
209         }
210         Msg->event_loop(1, 0.05);
211         Msg->event_loop(1, 0.05);
212
213         # disconnect users
214         foreach $dxchan (DXChannel->get_all()) {
215                 next if $dxchan->is_node;
216                 $dxchan->disconnect unless $dxchan == $DXProt::me;
217         }
218         Msg->event_loop(1, 0.05);
219         Msg->event_loop(1, 0.05);
220         Msg->event_loop(1, 0.05);
221         Msg->event_loop(1, 0.05);
222         Msg->event_loop(1, 0.05);
223         Msg->event_loop(1, 0.05);
224         DXUser::finish();
225         DXDupe::finish();
226
227         # close all databases
228         DXDb::closeall;
229
230         # close all listeners
231         for (@listeners) {
232                 $_->close_server;
233         }
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 #               Msg->pid_gone($cpid);
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                 $dxchan->disconnect if ($dxchan->{state} eq 'bye');
281         } elsif ($sort eq 'Z') {
282                 $dxchan->conn(undef);
283                 $dxchan->disconnect;
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-2001 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 use Listeners;
336
337 dbg('err', "starting listeners ...");
338 push @listeners, IntMsg->new_server("$clusteraddr", $clusterport, \&login);
339 dbg('err', "Internal port: $clusteraddr $clusterport");
340 for (@main::listen) {
341         push @listeners, ExtMsg->new_server($_->[0], $_->[1], \&login);
342         dbg('err', "External Port: $_->[0] $_->[1]");
343 }
344
345 # load bad words
346 dbg('err', "load badwords: " . (BadWords::load or "Ok"));
347
348 # prime some signals
349 unless ($^O =~ /^MS/) {
350         unless ($DB::VERSION) {
351                 $SIG{INT} = \&cease;
352                 $SIG{TERM} = \&cease;
353         }
354         $SIG{HUP} = 'IGNORE';
355         $SIG{CHLD} = sub { $zombies++ };
356         
357         $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
358         $SIG{IO} = sub {        dbg('err', "SIGIO received"); };
359         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
360         $SIG{KILL} = 'DEFAULT';     # as if it matters....
361
362         # catch the rest with a hopeful message
363         for (keys %SIG) {
364                 if (!$SIG{$_}) {
365                         #               dbg('chan', "Catching SIG $_");
366                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
367                 }
368         }
369 }
370
371 # start dupe system
372 DXDupe::init();
373
374 # read in system messages
375 DXM->init();
376
377 # read in command aliases
378 CmdAlias->init();
379
380 # initialise the Geomagnetic data engine
381 Geomag->init();
382 WCY->init();
383
384 # initial the Spot stuff
385 Spot->init();
386
387 # initialise the protocol engine
388 dbg('err', "reading in duplicate spot and WWV info ...");
389 DXProt->init();
390
391 # put in a DXCluster node for us here so we can add users and take them away
392 DXNode->new($DXProt::me, $mycall, 0, 1, $DXProt::myprot_version); 
393
394 # read in any existing message headers and clean out old crap
395 dbg('err', "reading existing message headers ...");
396 DXMsg->init();
397 DXMsg::clean_old();
398
399 # read in any cron jobs
400 dbg('err', "reading cron jobs ...");
401 DXCron->init();
402
403 # read in database descriptors
404 dbg('err', "reading database descriptors ...");
405 DXDb::load();
406
407 # starting local stuff
408 dbg('err', "doing local initialisation ...");
409 eval {
410         Local::init();
411 };
412 dbg('local', "Local::init error $@") if $@;
413
414 # print various flags
415 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
416
417 # this, such as it is, is the main loop!
418 dbg('err', "orft we jolly well go ...");
419
420 #open(DB::OUT, "|tee /tmp/aa");
421
422 for (;;) {
423 #       $DB::trace = 1;
424         
425         Msg->event_loop(1, 0.1);
426         my $timenow = time;
427         process_inqueue();                      # read in lines from the input queue and despatch them
428 #       $DB::trace = 0;
429         
430         # do timed stuff, ongoing processing happens one a second
431         if ($timenow != $systime) {
432                 reap if $zombies;
433                 $systime = $timenow;
434                 DXCron::process();      # do cron jobs
435                 DXCommandmode::process(); # process ongoing command mode stuff
436                 DXProt::process();              # process ongoing ak1a pcxx stuff
437                 DXConnect::process();
438                 DXMsg::process();
439                 DXDb::process();
440                 DXUser::process();
441                 DXDupe::process();
442                 
443                 eval { 
444                         Local::process();       # do any localised processing
445                 };
446                 dbg('local', "Local::process error $@") if $@;
447         }
448         if ($decease) {
449                 last if --$decease <= 0;
450         }
451 }
452 cease(0);
453 exit(0);
454
455