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