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