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