The guts of the new Msg system
[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 (DXChannel->get($call)) {
132                         my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call);
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 (DXCluster->get_exact($call)) {
143                                         my $mess = DXM::msg($lang, $user->is_node ? 'concluster' : 'conother', $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 (DXCluster->get_exact($call)) {
151                                 my $mess = DXM::msg($lang, 'conother', $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                         return;
163                 }
164
165                 # create the channel
166                 $dxchan = DXCommandmode->new($call, $conn, $user) if $user->is_user;
167                 $dxchan = DXProt->new($call, $conn, $user) if $user->is_node;
168                 $dxchan = BBS->new($call, $conn, $user) if $user->is_bbs;
169                 die "Invalid sort of user on $call = $sort" if !$dxchan;
170         }
171         
172         # queue the message and the channel object for later processing
173         if (defined $msg) {
174                 my $self = bless {}, "inqueue";
175                 $self->{dxchan} = $dxchan;
176                 $self->{data} = $msg;
177                 push @inqueue, $self;
178         }
179 }
180
181 sub login
182 {
183         return \&rec;
184 }
185
186 # cease running this program, close down all the connections nicely
187 sub cease
188 {
189         my $dxchan;
190
191         $SIG{'TERM'} = 'IGNORE';
192         $SIG{'INT'} = 'IGNORE';
193         
194         DXUser::sync;
195
196         eval {
197                 Local::finish();   # end local processing
198         };
199         dbg('local', "Local::finish error $@") if $@;
200
201         # disconnect nodes
202         foreach $dxchan (DXChannel->get_all()) {
203                 next unless $dxchan->is_node;
204             $dxchan->disconnect unless $dxchan == $DXProt::me;
205         }
206         Msg->event_loop(1, 0.05);
207         Msg->event_loop(1, 0.05);
208
209         # disconnect users
210         foreach $dxchan (DXChannel->get_all()) {
211                 next if $dxchan->is_node;
212                 $dxchan->disconnect unless $dxchan == $DXProt::me;
213         }
214         Msg->event_loop(1, 0.05);
215         Msg->event_loop(1, 0.05);
216         Msg->event_loop(1, 0.05);
217         Msg->event_loop(1, 0.05);
218         Msg->event_loop(1, 0.05);
219         Msg->event_loop(1, 0.05);
220         DXUser::finish();
221         DXDupe::finish();
222
223         # close all databases
224         DXDb::closeall;
225
226         # close all listeners
227         for (@listeners) {
228                 $_->close_server;
229         }
230
231         dbg('chan', "DXSpider version $version ended");
232         Log('cluster', "DXSpider V$version stopped");
233         dbgclose();
234         Logclose();
235         unlink $lockfn;
236 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
237         exit(0);
238 }
239
240 # the reaper of children
241 sub reap
242 {
243         my $cpid;
244         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
245                 dbg('reap', "cpid: $cpid");
246                 @outstanding_connects = grep {$_->{pid} != $cpid} @outstanding_connects;
247                 $zombies-- if $zombies > 0;
248         }
249         dbg('reap', "cpid: $cpid");
250 }
251
252 # this is where the input queue is dealt with and things are dispatched off to other parts of
253 # the cluster
254 sub process_inqueue
255 {
256         my $self = shift @inqueue;
257         return if !$self;
258         
259         my $data = $self->{data};
260         my $dxchan = $self->{dxchan};
261         my $error;
262         my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
263         return unless defined $sort;
264         
265         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
266         dbg('chan', "<- $sort $call $line\n") unless $sort eq 'D';
267
268         # handle A records
269         my $user = $dxchan->user;
270         if ($sort eq 'A' || $sort eq 'O') {
271                 $dxchan->start($line, $sort);  
272         } elsif ($sort eq 'I') {
273                 die "\$user not defined for $call" if !defined $user;
274                 # normal input
275                 $dxchan->normal($line);
276                 $dxchan->disconnect if ($dxchan->{state} eq 'bye');
277         } elsif ($sort eq 'Z') {
278                 $dxchan->conn(undef);
279                 $dxchan->disconnect;
280         } elsif ($sort eq 'D') {
281                 ;                       # ignored (an echo)
282         } else {
283                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
284         }
285 }
286
287 sub uptime
288 {
289         my $t = $systime - $starttime;
290         my $days = int $t / 86400;
291         $t -= $days * 86400;
292         my $hours = int $t / 3600;
293         $t -= $hours * 3600;
294         my $mins = int $t / 60;
295         return sprintf "%d %02d:%02d", $days, $hours, $mins;
296 }
297 #############################################################
298 #
299 # The start of the main line of code 
300 #
301 #############################################################
302
303 $starttime = $systime = time;
304 $lang = 'en' unless $lang;
305
306 # open the debug file, set various FHs to be unbuffered
307 dbginit();
308 foreach (@debug) {
309         dbgadd($_);
310 }
311 STDOUT->autoflush(1);
312
313 Log('cluster', "DXSpider V$version started");
314
315 # banner
316 dbg('err', "DXSpider DX Cluster Version $version", "Copyright (c) 1998-2001 Dirk Koopman G1TLH");
317
318 # load Prefixes
319 dbg('err', "loading prefixes ...");
320 Prefix::load();
321
322 # load band data
323 dbg('err', "loading band data ...");
324 Bands::load();
325
326 # initialise User file system
327 dbg('err', "loading user file system ..."); 
328 DXUser->init($userfn, 1);
329
330 # start listening for incoming messages/connects
331 use Listeners;
332
333 dbg('err', "starting listeners ...");
334 push @listeners, IntMsg->new_server("$clusteraddr", $clusterport, \&login);
335 dbg('err', "Internal port: $clusteraddr $clusterport");
336 for (@main::listen) {
337         push @listeners, ExtMsg->new_server($_->[0], $_->[1], \&login);
338         dbg('err', "External Port: $_->[0] $_->[1]");
339 }
340
341 # load bad words
342 dbg('err', "load badwords: " . (BadWords::load or "Ok"));
343
344 # prime some signals
345 unless ($^O =~ /^MS/) {
346         unless ($DB::VERSION) {
347                 $SIG{INT} = \&cease;
348                 $SIG{TERM} = \&cease;
349         }
350         $SIG{HUP} = 'IGNORE';
351         $SIG{CHLD} = sub { $zombies++ };
352         
353         $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
354         $SIG{IO} = sub {        dbg('err', "SIGIO received"); };
355         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
356         $SIG{KILL} = 'DEFAULT';     # as if it matters....
357
358         # catch the rest with a hopeful message
359         for (keys %SIG) {
360                 if (!$SIG{$_}) {
361                         #               dbg('chan', "Catching SIG $_");
362                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
363                 }
364         }
365 }
366
367 # start dupe system
368 DXDupe::init();
369
370 # read in system messages
371 DXM->init();
372
373 # read in command aliases
374 CmdAlias->init();
375
376 # initialise the Geomagnetic data engine
377 Geomag->init();
378 WCY->init();
379
380 # initial the Spot stuff
381 Spot->init();
382
383 # initialise the protocol engine
384 dbg('err', "reading in duplicate spot and WWV info ...");
385 DXProt->init();
386
387 # put in a DXCluster node for us here so we can add users and take them away
388 DXNode->new($DXProt::me, $mycall, 0, 1, $DXProt::myprot_version); 
389
390 # read in any existing message headers and clean out old crap
391 dbg('err', "reading existing message headers ...");
392 DXMsg->init();
393 DXMsg::clean_old();
394
395 # read in any cron jobs
396 dbg('err', "reading cron jobs ...");
397 DXCron->init();
398
399 # read in database descriptors
400 dbg('err', "reading database descriptors ...");
401 DXDb::load();
402
403 # starting local stuff
404 dbg('err', "doing local initialisation ...");
405 eval {
406         Local::init();
407 };
408 dbg('local', "Local::init error $@") if $@;
409
410 # print various flags
411 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
412
413 # this, such as it is, is the main loop!
414 dbg('err', "orft we jolly well go ...");
415
416 #open(DB::OUT, "|tee /tmp/aa");
417
418 for (;;) {
419 #       $DB::trace = 1;
420         
421         Msg->event_loop(1, 0.1);
422         my $timenow = time;
423         process_inqueue();                      # read in lines from the input queue and despatch them
424 #       $DB::trace = 0;
425         
426         # do timed stuff, ongoing processing happens one a second
427         if ($timenow != $systime) {
428                 reap if $zombies;
429                 $systime = $timenow;
430                 DXCron::process();      # do cron jobs
431                 DXCommandmode::process(); # process ongoing command mode stuff
432                 DXProt::process();              # process ongoing ak1a pcxx stuff
433                 DXConnect::process();
434                 DXMsg::process();
435                 DXDb::process();
436                 DXUser::process();
437                 DXDupe::process();
438                 
439                 eval { 
440                         Local::process();       # do any localised processing
441                 };
442                 dbg('local', "Local::process error $@") if $@;
443         }
444         if ($decease) {
445                 last if --$decease <= 0;
446         }
447 }
448 cease(0);
449 exit(0);
450
451