change select timeout
[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         my $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 IntMsg;
43 use ExtMsg;
44 use DXVars;
45 use DXDebug;
46 use DXLog;
47 use DXLogPrint;
48 use DXUtil;
49 use DXChannel;
50 use DXUser;
51 use DXM;
52 use DXCommandmode;
53 use DXProt;
54 use DXMsg;
55 use DXCluster;
56 use DXCron;
57 use DXConnect;
58 use Prefix;
59 use Bands;
60 use Geomag;
61 use CmdAlias;
62 use Filter;
63 use DXDb;
64 use AnnTalk;
65 use WCY;
66 use DXDupe;
67 use BadWords;
68
69 use Data::Dumper;
70 use Fcntl ':flock'; 
71 use POSIX ":sys_wait_h";
72
73 use Local;
74
75 package main;
76
77 use strict;
78 use vars qw(@inqueue $systime $version $starttime $lockfn @outstanding_connects $zombies $root
79                    @listeners $lang $myalias @debug $userfn $clusteraddr $clusterport $mycall $decease );
80
81 @inqueue = ();                                  # the main input queue, an array of hashes
82 $systime = 0;                                   # the time now (in seconds)
83 $version = "1.47";                              # the version no of the software
84 $starttime = 0;                 # the starting time of the cluster   
85 $lockfn = "cluster.lock";       # lock file name
86 #@outstanding_connects = ();     # list of outstanding connects
87 @listeners = ();                                # list of listeners
88
89       
90 # send a message to call on conn and disconnect
91 sub already_conn
92 {
93         my ($conn, $call, $mess) = @_;
94         
95         dbg('chan', "-> D $call $mess\n"); 
96         $conn->send_now("D$call|$mess");
97         sleep(2);
98         $conn->disconnect;
99 }
100
101 sub error_handler
102 {
103         my $dxchan = shift;
104         $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
105         $dxchan->disconnect;
106 }
107
108 # handle incoming messages
109 sub new_channel
110 {
111         my ($conn, $msg) = @_;
112         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
113         return unless defined $sort;
114         
115         # set up the basic channel info
116         # is there one already connected to me - locally? 
117         my $user = DXUser->get($call);
118         my $dxchan = DXChannel->get($call);
119         if ($dxchan) {
120                 my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call, $main::mycall);
121                 already_conn($conn, $call, $mess);
122                 return;
123         }
124         
125         # is there one already connected elsewhere in the cluster?
126         if ($user) {
127                 if (($user->is_node || $call eq $myalias) && !DXCluster->get_exact($call)) {
128                         ;
129                 } else {
130                         if (my $ref = DXCluster->get_exact($call)) {
131                                 my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->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 (my $ref = DXCluster->get_exact($call)) {
139                         my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->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->disconnect;
150                 return;
151         }
152
153         # create the channel
154         $dxchan = DXCommandmode->new($call, $conn, $user) if $user->is_user;
155         $dxchan = DXProt->new($call, $conn, $user) if $user->is_node;
156         $dxchan = BBS->new($call, $conn, $user) if $user->is_bbs;
157         die "Invalid sort of user on $call = $sort" if !$dxchan;
158
159         # check that the conn has a callsign
160         $conn->conns($call) if $conn->isa('IntMsg');
161
162         # set callbacks
163         $conn->set_error(sub {error_handler($dxchan)});
164         $conn->set_rproc(sub {my ($conn,$msg) = @_; rec($dxchan, $conn, $msg);});
165         rec($dxchan, $conn, $msg);
166 }
167
168 sub rec 
169 {
170         my ($dxchan, $conn, $msg) = @_;
171         
172         # queue the message and the channel object for later processing
173         if (defined $msg) {
174                 my $self = bless {}, "inqueue";
175                 $self->{dxchan} = $dxchan;
176                 $self->{data} = $msg;
177                 push @inqueue, $self;
178         }
179 }
180
181 sub login
182 {
183         return \&new_channel;
184 }
185
186 # cease running this program, close down all the connections nicely
187 sub cease
188 {
189         my $dxchan;
190
191         $SIG{'TERM'} = 'IGNORE';
192         $SIG{'INT'} = 'IGNORE';
193         
194         DXUser::sync;
195
196         eval {
197                 Local::finish();   # end local processing
198         };
199         dbg('local', "Local::finish error $@") if $@;
200
201         # disconnect nodes
202         foreach $dxchan (DXChannel->get_all()) {
203                 next unless $dxchan->is_node;
204             $dxchan->disconnect unless $dxchan == $DXProt::me;
205         }
206         Msg->event_loop(1, 0.05);
207         Msg->event_loop(1, 0.05);
208
209         # disconnect users
210         foreach $dxchan (DXChannel->get_all()) {
211                 next if $dxchan->is_node;
212                 $dxchan->disconnect unless $dxchan == $DXProt::me;
213         }
214         Msg->event_loop(1, 0.05);
215         Msg->event_loop(1, 0.05);
216         Msg->event_loop(1, 0.05);
217         Msg->event_loop(1, 0.05);
218         Msg->event_loop(1, 0.05);
219         Msg->event_loop(1, 0.05);
220         DXUser::finish();
221         DXDupe::finish();
222
223         # close all databases
224         DXDb::closeall;
225
226         # close all listeners
227         for (@listeners) {
228                 $_->close_server;
229         }
230
231         dbg('chan', "DXSpider version $version ended");
232         Log('cluster', "DXSpider V$version stopped");
233         dbgclose();
234         Logclose();
235         unlink $lockfn;
236 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
237         exit(0);
238 }
239
240 # the reaper of children
241 sub reap
242 {
243         my $cpid;
244         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
245                 dbg('reap', "cpid: $cpid");
246 #               Msg->pid_gone($cpid);
247                 $zombies-- if $zombies > 0;
248         }
249         dbg('reap', "cpid: $cpid");
250 }
251
252 # this is where the input queue is dealt with and things are dispatched off to other parts of
253 # the cluster
254 sub process_inqueue
255 {
256         my $self = shift @inqueue;
257         return if !$self;
258         
259         my $data = $self->{data};
260         my $dxchan = $self->{dxchan};
261         my $error;
262         my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
263         return unless defined $sort;
264         
265         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
266         dbg('chan', "<- $sort $call $line\n") unless $sort eq 'D';
267
268         # handle A records
269         my $user = $dxchan->user;
270         if ($sort eq 'A' || $sort eq 'O') {
271                 $dxchan->start($line, $sort);  
272         } elsif ($sort eq 'I') {
273                 die "\$user not defined for $call" if !defined $user;
274                 # normal input
275                 $dxchan->normal($line);
276                 $dxchan->disconnect if ($dxchan->{state} eq 'bye');
277         } elsif ($sort eq 'Z') {
278                 $dxchan->disconnect;
279         } elsif ($sort eq 'D') {
280                 ;                       # ignored (an echo)
281         } else {
282                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
283         }
284 }
285
286 sub uptime
287 {
288         my $t = $systime - $starttime;
289         my $days = int $t / 86400;
290         $t -= $days * 86400;
291         my $hours = int $t / 3600;
292         $t -= $hours * 3600;
293         my $mins = int $t / 60;
294         return sprintf "%d %02d:%02d", $days, $hours, $mins;
295 }
296 #############################################################
297 #
298 # The start of the main line of code 
299 #
300 #############################################################
301
302 $starttime = $systime = time;
303 $lang = 'en' unless $lang;
304
305 # open the debug file, set various FHs to be unbuffered
306 dbginit();
307 foreach (@debug) {
308         dbgadd($_);
309 }
310 STDOUT->autoflush(1);
311
312 Log('cluster', "DXSpider V$version started");
313
314 # banner
315 dbg('err', "DXSpider DX Cluster Version $version", "Copyright (c) 1998-2001 Dirk Koopman G1TLH");
316
317 # load Prefixes
318 dbg('err', "loading prefixes ...");
319 Prefix::load();
320
321 # load band data
322 dbg('err', "loading band data ...");
323 Bands::load();
324
325 # initialise User file system
326 dbg('err', "loading user file system ..."); 
327 DXUser->init($userfn, 1);
328
329 # start listening for incoming messages/connects
330 use Listeners;
331
332 dbg('err', "starting listeners ...");
333 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
334 $conn->conns("Server $clusteraddr/$clusterport");
335 push @listeners, $conn;
336 dbg('err', "Internal port: $clusteraddr $clusterport");
337 for (@main::listen) {
338         $conn = ExtMsg->new_server($_->[0], $_->[1], \&login);
339         $conn->conns("Server $_->[0]/$_->[1]");
340         push @listeners, $conn;
341         dbg('err', "External Port: $_->[0] $_->[1]");
342 }
343
344 # load bad words
345 dbg('err', "load badwords: " . (BadWords::load or "Ok"));
346
347 # prime some signals
348 unless ($^O =~ /^MS/) {
349         unless ($DB::VERSION) {
350                 $SIG{INT} = \&cease;
351                 $SIG{TERM} = \&cease;
352         }
353         $SIG{HUP} = 'IGNORE';
354         $SIG{CHLD} = sub { $zombies++ };
355         
356         $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
357         $SIG{IO} = sub {        dbg('err', "SIGIO received"); };
358         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
359         $SIG{KILL} = 'DEFAULT';     # as if it matters....
360
361         # catch the rest with a hopeful message
362         for (keys %SIG) {
363                 if (!$SIG{$_}) {
364                         #               dbg('chan', "Catching SIG $_");
365                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
366                 }
367         }
368 }
369
370 # start dupe system
371 DXDupe::init();
372
373 # read in system messages
374 DXM->init();
375
376 # read in command aliases
377 CmdAlias->init();
378
379 # initialise the Geomagnetic data engine
380 Geomag->init();
381 WCY->init();
382
383 # initial the Spot stuff
384 Spot->init();
385
386 # initialise the protocol engine
387 dbg('err', "reading in duplicate spot and WWV info ...");
388 DXProt->init();
389
390 # put in a DXCluster node for us here so we can add users and take them away
391 DXNode->new($DXProt::me, $mycall, 0, 1, $DXProt::myprot_version); 
392
393 # read in any existing message headers and clean out old crap
394 dbg('err', "reading existing message headers ...");
395 DXMsg->init();
396 DXMsg::clean_old();
397
398 # read in any cron jobs
399 dbg('err', "reading cron jobs ...");
400 DXCron->init();
401
402 # read in database descriptors
403 dbg('err', "reading database descriptors ...");
404 DXDb::load();
405
406 # starting local stuff
407 dbg('err', "doing local initialisation ...");
408 eval {
409         Local::init();
410 };
411 dbg('local', "Local::init error $@") if $@;
412
413 # print various flags
414 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
415
416 # this, such as it is, is the main loop!
417 dbg('err', "orft we jolly well go ...");
418
419 #open(DB::OUT, "|tee /tmp/aa");
420
421 for (;;) {
422 #       $DB::trace = 1;
423         
424         Msg->event_loop(10, 0.010);
425         my $timenow = time;
426         process_inqueue();                      # read in lines from the input queue and despatch them
427 #       $DB::trace = 0;
428         
429         # do timed stuff, ongoing processing happens one a second
430         if ($timenow != $systime) {
431                 reap if $zombies;
432                 $systime = $timenow;
433                 DXCron::process();      # do cron jobs
434                 DXCommandmode::process(); # process ongoing command mode stuff
435                 DXProt::process();              # process ongoing ak1a pcxx stuff
436                 DXConnect::process();
437                 DXMsg::process();
438                 DXDb::process();
439                 DXUser::process();
440                 DXDupe::process();
441                 
442                 eval { 
443                         Local::process();       # do any localised processing
444                 };
445                 dbg('local', "Local::process error $@") if $@;
446         }
447         if ($decease) {
448                 last if --$decease <= 0;
449         }
450 }
451 cease(0);
452 exit(0);
453
454