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