a46e3b2d58f692e9905666b4618484a47c8be18a
[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.36";                              # 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                 if ($dxchan) {
108                         $dxchan->disconnect;
109                 }
110                 return;
111         }
112         
113         # set up the basic channel info - this needs a bit more thought - there is duplication here
114         if (!defined $dxchan) {
115                 my ($sort, $call, $line) = $msg =~ /^(\w)(\S+)\|(.*)$/;
116                 my ($scall, $ssid) = split /-/, $call;
117                 
118                 # adjust the callsign if it has an SSID, SSID <= 8 are legal > 8 are netrom connections
119         if ($ssid) {
120                         $ssid = 15 if $ssid > 15;
121                         if ($ssid > 8) {
122                                 $ssid = 15 - $ssid;
123                                 $call = "$scall-$ssid";
124                         }
125                 }
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->sort eq 'A') ? '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->sort eq 'A' || $call eq $myalias) && !DXCluster->get_exact($call)) {
138                                 ;
139                         } else {
140                                 if (DXCluster->get_exact($call)) {
141                                         my $mess = DXM::msg($lang, $user->sort eq 'A' ? '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->sort eq 'U');
165                 $dxchan = DXProt->new($call, $conn, $user) if ($user->sort eq 'A');
166                 $dxchan = BBS->new($call, $conn, $user) if ($user->sort eq 'B');
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         eval {
193                 Local::finish();   # end local processing
194         };
195         dbg('local', "Local::finish error $@") if $@;
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
209         # disconnect users
210         foreach $dxchan (DXChannel->get_all()) {
211                 next if $dxchan->is_ak1a;
212                 disconnect($dxchan) unless $dxchan == $DXProt::me;
213         }
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         Msg->event_loop(1, 0.05);
219         Msg->event_loop(1, 0.05);
220         DXUser::finish();
221
222         # close all databases
223         DXDb::closeall;
224         
225         dbg('chan', "DXSpider version $version ended");
226         Log('cluster', "DXSpider V$version stopped");
227         dbgclose();
228         Logclose();
229         unlink $lockfn;
230 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
231         exit(0);
232 }
233
234 # the reaper of children
235 sub reap
236 {
237         $SIG{'CHLD'} = \&reap;
238         my $cpid = wait;
239         @outstanding_connects = grep {$_->{pid} != $cpid} @outstanding_connects;
240 }
241
242 # this is where the input queue is dealt with and things are dispatched off to other parts of
243 # the cluster
244 sub process_inqueue
245 {
246         my $self = shift @inqueue;
247         return if !$self;
248         
249         my $data = $self->{data};
250         my $dxchan = $self->{dxchan};
251         my ($sort, $call, $line) = $data =~ /^(\w)([A-Z0-9\-]+)\|(.*)$/;
252         my $error;
253         
254         # the above regexp must work
255         return unless ($sort && $call && $line);
256         
257         # translate any crappy characters into hex characters 
258         if ($line =~ /[\x00-\x06\x08\x0a-\x1f\x7f-\xff]/o) {
259                 $line =~ s/([\x00-\x1f\x7f-\xff])/uc sprintf("%%%02x",ord($1))/eg;
260         }
261         
262         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
263         dbg('chan', "<- $sort $call $line\n") unless $sort eq 'D';
264
265         # handle A records
266         my $user = $dxchan->user;
267         if ($sort eq 'A' || $sort eq 'O') {
268                 $dxchan->start($line, $sort);  
269         } elsif ($sort eq 'I') {
270                 die "\$user not defined for $call" if !defined $user;
271                 # normal input
272                 $dxchan->normal($line);
273                 disconnect($dxchan) if ($dxchan->{state} eq 'bye');
274         } elsif ($sort eq 'Z') {
275                 $dxchan->conn(undef);
276                 disconnect($dxchan);
277         } elsif ($sort eq 'D') {
278                 ;                       # ignored (an echo)
279         } else {
280                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
281         }
282 }
283
284 sub uptime
285 {
286         my $t = $systime - $starttime;
287         my $days = int $t / 86400;
288         $t -= $days * 86400;
289         my $hours = int $t / 3600;
290         $t -= $hours * 3600;
291         my $mins = int $t / 60;
292         return sprintf "%d %02d:%02d", $days, $hours, $mins;
293 }
294 #############################################################
295 #
296 # The start of the main line of code 
297 #
298 #############################################################
299
300 $starttime = $systime = time;
301
302 # open the debug file, set various FHs to be unbuffered
303 dbginit();
304 foreach (@debug) {
305         dbgadd($_);
306 }
307 STDOUT->autoflush(1);
308
309 Log('cluster', "DXSpider V$version started");
310
311 # banner
312 print "DXSpider DX Cluster Version $version\nCopyright (c) 1998-1999 Dirk Koopman G1TLH\n";
313
314 # load Prefixes
315 print "loading prefixes ...\n";
316 Prefix::load();
317
318 # load band data
319 print "loading band data ...\n";
320 Bands::load();
321
322 # initialise User file system
323 print "loading user file system ...\n"; 
324 DXUser->init($userfn, 1);
325
326 # start listening for incoming messages/connects
327 print "starting listener ...\n";
328 Msg->new_server("$clusteraddr", $clusterport, \&login);
329
330 # prime some signals
331 $SIG{'INT'} = \&cease;
332 $SIG{'TERM'} = \&cease;
333 $SIG{'HUP'} = 'IGNORE';
334 $SIG{'CHLD'} = \&reap;
335
336 # read in system messages
337 DXM->init();
338
339 # read in command aliases
340 CmdAlias->init();
341
342 # initialise the Geomagnetic data engine
343 Geomag->init();
344
345 # initial the Spot stuff
346 Spot->init();
347
348 # initialise the protocol engine
349 print "reading in duplicate spot and WWV info ...\n";
350 DXProt->init();
351
352
353 # put in a DXCluster node for us here so we can add users and take them away
354 DXNode->new(0, $mycall, 0, 1, $DXProt::myprot_version); 
355
356 # read in any existing message headers and clean out old crap
357 print "reading existing message headers ...\n";
358 DXMsg->init();
359 DXMsg::clean_old();
360
361 # read in any cron jobs
362 print "reading cron jobs ...\n";
363 DXCron->init();
364
365 # read in database descriptors
366 print "reading database descriptors ...\n";
367 DXDb::load();
368
369 # starting local stuff
370 print "doing local initialisation ...\n";
371 eval {
372         Local::init();
373 };
374 dbg('local', "Local::init error $@") if $@;
375
376 # print various flags
377 #print "useful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P\n";
378
379 # this, such as it is, is the main loop!
380 print "orft we jolly well go ...\n";
381 dbg('chan', "DXSpider version $version started...");
382 for (;;) {
383         my $timenow;
384         Msg->event_loop(1, 0.1);
385         $timenow = time;
386         process_inqueue();                      # read in lines from the input queue and despatch them
387         
388         # do timed stuff, ongoing processing happens one a second
389         if ($timenow != $systime) {
390                 $systime = $timenow;
391                 $cldate = &cldate();
392                 $ztime = &ztime();
393                 DXCron::process();      # do cron jobs
394                 DXCommandmode::process(); # process ongoing command mode stuff
395                 DXProt::process();              # process ongoing ak1a pcxx stuff
396                 DXConnect::process();
397                 DXMsg::process();
398                 DXDb::process();
399                 eval { 
400                         Local::process();       # do any localised processing
401                 };
402                 dbg('local', "Local::process error $@") if $@;
403         }
404         if ($decease) {
405                 last if --$decease <= 0;
406         }
407 }
408 cease(0);
409 exit(0);
410
411