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