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