dd12a9dfe22dc564058cadadb463bde7994f281a
[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                 if ($dxchan) {
108                         disconnect($dxchan);
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
117                 # is there one already connected to me ? 
118                 my $user = DXUser->get($call);
119                 if (DXChannel->get($call)) {
120                         my $mess = DXM::msg($lang, $user->sort eq 'A' ? 'concluster' : 'conother', $call);
121                         already_conn($conn, $call, $mess);
122                         return;
123                 }
124                 
125                 # is there one already connected elsewhere in the cluster (and not a cluster)
126                 if ($user) {
127                         if (($user->sort eq 'A' || $call eq $myalias) && !DXCluster->get_exact($call)) {
128                                 ;
129                         } else {
130                                 if (DXCluster->get($call) || DXChannel->get($call)) {
131                                         my $mess = DXM::msg($lang, $user->sort eq 'A' ? 'concluster' : 'conother', $call);
132                                         already_conn($conn, $call, $mess);
133                                         return;
134                                 }
135                         }
136                         $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
137                 } else {
138                         if (DXCluster->get($call)) {
139                                 my $mess = DXM::msg($lang, 'conother', $call);
140                                 already_conn($conn, $call, $mess);
141                                 return;
142                         }
143                         $user = DXUser->new($call);
144                 }
145
146                 # is he locked out ?
147                 if ($user->lockout) {
148                         Log('DXCommand', "$call is locked out, disconnected");
149                         $conn->send_now("Z$call|bye"); # this will cause 'client' to disconnect
150                         return;
151                 }
152
153                 # create the channel
154                 $dxchan = DXCommandmode->new($call, $conn, $user) if ($user->sort eq 'U');
155                 $dxchan = DXProt->new($call, $conn, $user) if ($user->sort eq 'A');
156                 $dxchan = BBS->new($call, $conn, $user) if ($user->sort eq 'B');
157                 die "Invalid sort of user on $call = $sort" if !$dxchan;
158         }
159         
160         # queue the message and the channel object for later processing
161         if (defined $msg) {
162                 my $self = bless {}, "inqueue";
163                 $self->{dxchan} = $dxchan;
164                 $self->{data} = $msg;
165                 push @inqueue, $self;
166         }
167 }
168
169 sub login
170 {
171         return \&rec;
172 }
173
174 # cease running this program, close down all the connections nicely
175 sub cease
176 {
177         my $dxchan;
178
179         $SIG{'TERM'} = 'IGNORE';
180         $SIG{'INT'} = 'IGNORE';
181         
182         eval {
183                 Local::finish();   # end local processing
184         };
185         dbg('local', "Local::finish error $@") if $@;
186
187         # disconnect users
188         foreach $dxchan (DXChannel->get_all()) {
189                 next if $dxchan->is_ak1a;
190                 disconnect($dxchan) unless $dxchan == $DXProt::me;
191         }
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         Msg->event_loop(1, 0.05);
197         Msg->event_loop(1, 0.05);
198
199         # disconnect nodes
200         foreach $dxchan (DXChannel->get_all()) {
201                 next unless $dxchan->is_ak1a;
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         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         Msg->event_loop(1, 0.05);
215         Msg->event_loop(1, 0.05);
216         DXUser::finish();
217
218         # close all databases
219         DXDb::closeall;
220         
221         dbg('chan', "DXSpider version $version ended");
222         Log('cluster', "DXSpider V$version stopped");
223         dbgclose();
224         Logclose();
225         unlink $lockfn;
226 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
227         exit(0);
228 }
229
230 # the reaper of children
231 sub reap
232 {
233         $SIG{'CHLD'} = \&reap;
234         my $cpid = wait;
235         @outstanding_connects = grep {$_->{pid} != $cpid} @outstanding_connects;
236 }
237
238 # this is where the input queue is dealt with and things are dispatched off to other parts of
239 # the cluster
240 sub process_inqueue
241 {
242         my $self = shift @inqueue;
243         return if !$self;
244         
245         my $data = $self->{data};
246         my $dxchan = $self->{dxchan};
247         my ($sort, $call, $line) = $data =~ /^(\w)([A-Z0-9\-]+)\|(.*)$/;
248         my $error;
249         
250         # the above regexp must work
251         return unless ($sort && $call && $line);
252         
253         # translate any crappy characters into hex characters 
254         if ($line =~ /[\x00-\x06\x08\x0a-\x1f\x7f-\xff]/o) {
255                 $line =~ s/([\x00-\x1f\x7f-\xff])/uc sprintf("%%%02x",ord($1))/eg;
256         }
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 print "DXSpider DX Cluster Version $version\nCopyright (c) 1998 Dirk Koopman G1TLH\n";
309
310 # load Prefixes
311 print "loading prefixes ...\n";
312 Prefix::load();
313
314 # load band data
315 print "loading band data ...\n";
316 Bands::load();
317
318 # initialise User file system
319 print "loading user file system ...\n"; 
320 DXUser->init($userfn, 1);
321
322 # start listening for incoming messages/connects
323 print "starting listener ...\n";
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 # read in system messages
333 DXM->init();
334
335 # read in command aliases
336 CmdAlias->init();
337
338 # initialise the Geomagnetic data engine
339 Geomag->init();
340
341 # initial the Spot stuff
342 Spot->init();
343
344 # initialise the protocol engine
345 print "reading in duplicate spot and WWV info ...\n";
346 DXProt->init();
347
348
349 # put in a DXCluster node for us here so we can add users and take them away
350 DXNode->new(0, $mycall, 0, 1, $DXProt::myprot_version); 
351
352 # read in any existing message headers and clean out old crap
353 print "reading existing message headers ...\n";
354 DXMsg->init();
355 DXMsg::clean_old();
356
357 # read in any cron jobs
358 print "reading cron jobs ...\n";
359 DXCron->init();
360
361 # read in database descriptors
362 print "reading database descriptors ...\n";
363 DXDb::load();
364
365 # starting local stuff
366 print "doing local initialisation ...\n";
367 eval {
368         Local::init();
369 };
370 dbg('local', "Local::init error $@") if $@;
371
372 # print various flags
373 #print "useful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P\n";
374
375 # this, such as it is, is the main loop!
376 print "orft we jolly well go ...\n";
377 dbg('chan', "DXSpider version $version started...");
378 for (;;) {
379         my $timenow;
380         Msg->event_loop(1, 0.1);
381         $timenow = time;
382         process_inqueue();                      # read in lines from the input queue and despatch them
383         
384         # do timed stuff, ongoing processing happens one a second
385         if ($timenow != $systime) {
386                 $systime = $timenow;
387                 $cldate = &cldate();
388                 $ztime = &ztime();
389                 DXCron::process();      # do cron jobs
390                 DXCommandmode::process(); # process ongoing command mode stuff
391                 DXProt::process();              # process ongoing ak1a pcxx stuff
392                 DXConnect::process();
393                 DXMsg::process();
394                 DXDb::process();
395                 eval { 
396                         Local::process();       # do any localised processing
397                 };
398                 dbg('local', "Local::process error $@") if $@;
399         }
400         if ($decease) {
401                 last if --$decease <= 0;
402         }
403 }
404 cease(0);
405 exit(0);
406
407