add a first cut at an incoming only AGW engine shim for M$
[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 AGWMsg;
45 use DXVars;
46 use DXDebug;
47 use DXLog;
48 use DXLogPrint;
49 use DXUtil;
50 use DXChannel;
51 use DXUser;
52 use DXM;
53 use DXCommandmode;
54 use DXProt;
55 use DXMsg;
56 use DXCluster;
57 use DXCron;
58 use DXConnect;
59 use Prefix;
60 use Bands;
61 use Geomag;
62 use CmdAlias;
63 use Filter;
64 use DXDb;
65 use AnnTalk;
66 use WCY;
67 use DXDupe;
68 use BadWords;
69
70 use Data::Dumper;
71 use IO::File;
72 use Fcntl ':flock'; 
73 use POSIX ":sys_wait_h";
74
75 use Local;
76
77 package main;
78
79 use strict;
80 use vars qw(@inqueue $systime $version $starttime $lockfn @outstanding_connects 
81                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr 
82                         $clusterport $mycall $decease $build
83                    );
84
85 @inqueue = ();                                  # the main input queue, an array of hashes
86 $systime = 0;                                   # the time now (in seconds)
87 $version = "1.47";                              # the version no of the software
88 $starttime = 0;                 # the starting time of the cluster   
89 $lockfn = "cluster.lock";       # lock file name
90 #@outstanding_connects = ();     # list of outstanding connects
91 @listeners = ();                                # list of listeners
92
93       
94 # send a message to call on conn and disconnect
95 sub already_conn
96 {
97         my ($conn, $call, $mess) = @_;
98         
99         dbg('chan', "-> D $call $mess\n"); 
100         $conn->send_now("D$call|$mess");
101         Msg->sleep(2);
102         $conn->disconnect;
103 }
104
105 sub error_handler
106 {
107         my $dxchan = shift;
108         $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
109         $dxchan->disconnect(1);
110 }
111
112 # handle incoming messages
113 sub new_channel
114 {
115         my ($conn, $msg) = @_;
116         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
117         return unless defined $sort;
118         
119         # set up the basic channel info
120         # is there one already connected to me - locally? 
121         my $user = DXUser->get($call);
122         my $dxchan = DXChannel->get($call);
123         if ($dxchan) {
124                 my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call, $main::mycall);
125                 already_conn($conn, $call, $mess);
126                 return;
127         }
128         
129         # is there one already connected elsewhere in the cluster?
130         if ($user) {
131                 if (($user->is_node || $call eq $myalias) && !DXCluster->get_exact($call)) {
132                         ;
133                 } else {
134                         if (my $ref = DXCluster->get_exact($call)) {
135                                 my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->call);
136                                 already_conn($conn, $call, $mess);
137                                 return;
138                         }
139                 }
140                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
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                 $user = DXUser->new($call);
148         }
149         
150         # is he locked out ?
151         if ($user->lockout) {
152                 Log('DXCommand', "$call is locked out, disconnected");
153                 $conn->disconnect;
154                 return;
155         }
156
157         # create the channel
158         $dxchan = DXCommandmode->new($call, $conn, $user) if $user->is_user;
159         $dxchan = DXProt->new($call, $conn, $user) if $user->is_node;
160         $dxchan = BBS->new($call, $conn, $user) if $user->is_bbs;
161         die "Invalid sort of user on $call = $sort" if !$dxchan;
162
163         # check that the conn has a callsign
164         $conn->conns($call) if $conn->isa('IntMsg');
165
166         # set callbacks
167         $conn->set_error(sub {error_handler($dxchan)});
168         $conn->set_rproc(sub {my ($conn,$msg) = @_; rec($dxchan, $conn, $msg);});
169         rec($dxchan, $conn, $msg);
170 }
171
172 sub rec 
173 {
174         my ($dxchan, $conn, $msg) = @_;
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 \&new_channel;
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
219         # disconnect AGW
220         AGWMsg::finish();
221         
222         Msg->event_loop(1, 0.05);
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         DXUser::finish();
229         DXDupe::finish();
230
231         # close all databases
232         DXDb::closeall;
233
234         # close all listeners
235         for (@listeners) {
236                 $_->close_server;
237         }
238
239         dbg('chan', "DXSpider version $version, build $build ended");
240         Log('cluster', "DXSpider V$version, build $build ended");
241         dbgclose();
242         Logclose();
243         unlink $lockfn;
244 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
245         exit(0);
246 }
247
248 # the reaper of children
249 sub reap
250 {
251         my $cpid;
252         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
253                 dbg('reap', "cpid: $cpid");
254 #               Msg->pid_gone($cpid);
255                 $zombies-- if $zombies > 0;
256         }
257         dbg('reap', "cpid: $cpid");
258 }
259
260 # this is where the input queue is dealt with and things are dispatched off to other parts of
261 # the cluster
262 sub process_inqueue
263 {
264         my $self = shift @inqueue;
265         return if !$self;
266         
267         my $data = $self->{data};
268         my $dxchan = $self->{dxchan};
269         my $error;
270         my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
271         return unless defined $sort;
272         
273         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
274         dbg('chan', "<- $sort $call $line\n") unless $sort eq 'D';
275
276         # handle A records
277         my $user = $dxchan->user;
278         if ($sort eq 'A' || $sort eq 'O') {
279                 $dxchan->start($line, $sort);  
280         } elsif ($sort eq 'I') {
281                 die "\$user not defined for $call" if !defined $user;
282                 # normal input
283                 $dxchan->normal($line);
284                 $dxchan->disconnect if ($dxchan->{state} eq 'bye');
285         } elsif ($sort eq 'Z') {
286                 $dxchan->disconnect;
287         } elsif ($sort eq 'D') {
288                 ;                       # ignored (an echo)
289         } else {
290                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
291         }
292 }
293
294 sub uptime
295 {
296         my $t = $systime - $starttime;
297         my $days = int $t / 86400;
298         $t -= $days * 86400;
299         my $hours = int $t / 3600;
300         $t -= $hours * 3600;
301         my $mins = int $t / 60;
302         return sprintf "%d %02d:%02d", $days, $hours, $mins;
303 }
304 #############################################################
305 #
306 # The start of the main line of code 
307 #
308 #############################################################
309
310 $starttime = $systime = time;
311 $lang = 'en' unless $lang;
312
313 # open the debug file, set various FHs to be unbuffered
314 dbginit();
315 foreach (@debug) {
316         dbgadd($_);
317 }
318 STDOUT->autoflush(1);
319
320 # calculate build number
321 $build = $main::version;
322
323 if (opendir(DIR, "$main::root/perl")) {
324         my @d = readdir(DIR);
325         closedir(DIR);
326         foreach my $fn (@d) {
327                 if ($fn =~ /^cluster\.pl$/ || $fn =~ /\.pm$/) {
328                         my $f = new IO::File "$main::root/perl/$fn" or next;
329                         while (<$f>) {
330                                 if (/^#\s+\$Id:\s+[\w\._]+,v\s+(\d+\.\d+)/ ) {
331                                         $build += $1;
332                                         last;
333                                 }
334                         }
335                         $f->close;
336                 }
337         }
338 }
339
340 Log('cluster', "DXSpider V$version, build $build started");
341
342 # banner
343 dbg('err', "DXSpider Version $version, build $build started", "Copyright (c) 1998-2001 Dirk Koopman G1TLH");
344
345 # load Prefixes
346 dbg('err', "loading prefixes ...");
347 Prefix::load();
348
349 # load band data
350 dbg('err', "loading band data ...");
351 Bands::load();
352
353 # initialise User file system
354 dbg('err', "loading user file system ..."); 
355 DXUser->init($userfn, 1);
356
357 # start listening for incoming messages/connects
358 use Listeners;
359
360 dbg('err', "starting listeners ...");
361 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
362 $conn->conns("Server $clusteraddr/$clusterport");
363 push @listeners, $conn;
364 dbg('err', "Internal port: $clusteraddr $clusterport");
365 for (@main::listen) {
366         $conn = ExtMsg->new_server($_->[0], $_->[1], \&login);
367         $conn->conns("Server $_->[0]/$_->[1]");
368         push @listeners, $conn;
369         dbg('err', "External Port: $_->[0] $_->[1]");
370 }
371 AGWMsg::init(\&new_channel);
372
373 # load bad words
374 dbg('err', "load badwords: " . (BadWords::load or "Ok"));
375
376 # prime some signals
377 unless ($^O =~ /^MS/) {
378         unless ($DB::VERSION) {
379                 $SIG{INT} = \&cease;
380                 $SIG{TERM} = \&cease;
381         }
382         $SIG{HUP} = 'IGNORE';
383         $SIG{CHLD} = sub { $zombies++ };
384         
385         $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
386         $SIG{IO} = sub {        dbg('err', "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('chan', "Catching SIG $_");
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('err', "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 DXNode->new($DXProt::me, $mycall, 0, 1, $DXProt::myprot_version); 
421
422 # read in any existing message headers and clean out old crap
423 dbg('err', "reading existing message headers ...");
424 DXMsg->init();
425 DXMsg::clean_old();
426
427 # read in any cron jobs
428 dbg('err', "reading cron jobs ...");
429 DXCron->init();
430
431 # read in database descriptors
432 dbg('err', "reading database descriptors ...");
433 DXDb::load();
434
435 # starting local stuff
436 dbg('err', "doing local initialisation ...");
437 eval {
438         Local::init();
439 };
440 dbg('local', "Local::init error $@") if $@;
441
442 # print various flags
443 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
444
445 # this, such as it is, is the main loop!
446 dbg('err', "orft we jolly well go ...");
447
448 #open(DB::OUT, "|tee /tmp/aa");
449
450 for (;;) {
451 #       $DB::trace = 1;
452         
453         Msg->event_loop(10, 0.010);
454         my $timenow = time;
455         process_inqueue();                      # read in lines from the input queue and despatch them
456 #       $DB::trace = 0;
457         
458         # do timed stuff, ongoing processing happens one a second
459         if ($timenow != $systime) {
460                 reap if $zombies;
461                 $systime = $timenow;
462                 DXCron::process();      # do cron jobs
463                 DXCommandmode::process(); # process ongoing command mode stuff
464                 DXProt::process();              # process ongoing ak1a pcxx stuff
465                 DXConnect::process();
466                 DXMsg::process();
467                 DXDb::process();
468                 DXUser::process();
469                 DXDupe::process();
470                 
471                 eval { 
472                         Local::process();       # do any localised processing
473                 };
474                 dbg('local', "Local::process error $@") if $@;
475         }
476         if ($decease) {
477                 last if --$decease <= 0;
478         }
479 }
480 cease(0);
481 exit(0);
482
483