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