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