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