do non blocking connects
[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 #                  $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->disconnect;
105 }
106
107 # handle incoming messages
108 sub rec
109 {
110         my ($conn, $msg) = @_;
111         my $dxchan = DXChannel->get_by_cnum($conn); # get the dxconnnect object for this message
112         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
113         return unless defined $sort;
114         
115         # set up the basic channel info
116         if (!defined $dxchan) {
117
118                 # is there one already connected to me - locally? 
119                 my $user = DXUser->get($call);
120                 if ($sort ne 'O' && Msg->conns($call)) {
121                         my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call, $main::mycall);
122                         already_conn($conn, $call, $mess);
123                         return;
124                 }
125                 
126                 # is there one already connected elsewhere in the cluster?
127                 if ($user) {
128                         if (($user->is_node || $call eq $myalias) && !DXCluster->get_exact($call)) {
129                                 ;
130                         } else {
131                                 if (my $ref = DXCluster->get_exact($call)) {
132                                         my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->call);
133                                         already_conn($conn, $call, $mess);
134                                         return;
135                                 }
136                         }
137                         $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
138                 } else {
139                         if (my $ref = DXCluster->get_exact($call)) {
140                                 my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->call);
141                                 already_conn($conn, $call, $mess);
142                                 return;
143                         }
144                         $user = DXUser->new($call);
145                 }
146
147                 # is he locked out ?
148                 if ($user->lockout) {
149                         Log('DXCommand', "$call is locked out, disconnected");
150                         $conn->disconnect;
151                         return;
152                 }
153
154                 # mark him up
155                 $conn->conns($call) unless $sort eq 'O';
156                 $conn->set_error(sub {error_handler($dxchan)});
157                 
158                 # create the channel
159                 $dxchan = DXCommandmode->new($call, $conn, $user) if $user->is_user;
160                 $dxchan = DXProt->new($call, $conn, $user) if $user->is_node;
161                 $dxchan = BBS->new($call, $conn, $user) if $user->is_bbs;
162                 die "Invalid sort of user on $call = $sort" if !$dxchan;
163         }
164         
165         # queue the message and the channel object for later processing
166         if (defined $msg) {
167                 my $self = bless {}, "inqueue";
168                 $self->{dxchan} = $dxchan;
169                 $self->{data} = $msg;
170                 push @inqueue, $self;
171         }
172 }
173
174 sub login
175 {
176         return \&rec;
177 }
178
179 # cease running this program, close down all the connections nicely
180 sub cease
181 {
182         my $dxchan;
183
184         $SIG{'TERM'} = 'IGNORE';
185         $SIG{'INT'} = 'IGNORE';
186         
187         DXUser::sync;
188
189         eval {
190                 Local::finish();   # end local processing
191         };
192         dbg('local', "Local::finish error $@") if $@;
193
194         # disconnect nodes
195         foreach $dxchan (DXChannel->get_all()) {
196                 next unless $dxchan->is_node;
197             $dxchan->disconnect unless $dxchan == $DXProt::me;
198         }
199         Msg->event_loop(1, 0.05);
200         Msg->event_loop(1, 0.05);
201
202         # disconnect users
203         foreach $dxchan (DXChannel->get_all()) {
204                 next if $dxchan->is_node;
205                 $dxchan->disconnect unless $dxchan == $DXProt::me;
206         }
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         DXDupe::finish();
215
216         # close all databases
217         DXDb::closeall;
218
219         # close all listeners
220         for (@listeners) {
221                 $_->close_server;
222         }
223
224         dbg('chan', "DXSpider version $version ended");
225         Log('cluster', "DXSpider V$version stopped");
226         dbgclose();
227         Logclose();
228         unlink $lockfn;
229 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
230         exit(0);
231 }
232
233 # the reaper of children
234 sub reap
235 {
236         my $cpid;
237         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
238                 dbg('reap', "cpid: $cpid");
239 #               Msg->pid_gone($cpid);
240                 $zombies-- if $zombies > 0;
241         }
242         dbg('reap', "cpid: $cpid");
243 }
244
245 # this is where the input queue is dealt with and things are dispatched off to other parts of
246 # the cluster
247 sub process_inqueue
248 {
249         my $self = shift @inqueue;
250         return if !$self;
251         
252         my $data = $self->{data};
253         my $dxchan = $self->{dxchan};
254         my $error;
255         my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
256         return unless defined $sort;
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                 $dxchan->disconnect if ($dxchan->{state} eq 'bye');
270         } elsif ($sort eq 'Z') {
271                 $dxchan->conn(undef);
272                 $dxchan->disconnect;
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 $lang = 'en' unless $lang;
298
299 # open the debug file, set various FHs to be unbuffered
300 dbginit();
301 foreach (@debug) {
302         dbgadd($_);
303 }
304 STDOUT->autoflush(1);
305
306 Log('cluster', "DXSpider V$version started");
307
308 # banner
309 dbg('err', "DXSpider DX Cluster Version $version", "Copyright (c) 1998-2001 Dirk Koopman G1TLH");
310
311 # load Prefixes
312 dbg('err', "loading prefixes ...");
313 Prefix::load();
314
315 # load band data
316 dbg('err', "loading band data ...");
317 Bands::load();
318
319 # initialise User file system
320 dbg('err', "loading user file system ..."); 
321 DXUser->init($userfn, 1);
322
323 # start listening for incoming messages/connects
324 use Listeners;
325
326 dbg('err', "starting listeners ...");
327 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
328 $conn->conns("Server $clusteraddr/$clusterport");
329 push @listeners, $conn;
330 dbg('err', "Internal port: $clusteraddr $clusterport");
331 for (@main::listen) {
332         $conn = ExtMsg->new_server($_->[0], $_->[1], \&login);
333         $conn->conns("Server $_->[0]/$_->[1]");
334         push @listeners, $conn;
335         dbg('err', "External Port: $_->[0] $_->[1]");
336 }
337
338 # load bad words
339 dbg('err', "load badwords: " . (BadWords::load or "Ok"));
340
341 # prime some signals
342 unless ($^O =~ /^MS/) {
343         unless ($DB::VERSION) {
344                 $SIG{INT} = \&cease;
345                 $SIG{TERM} = \&cease;
346         }
347         $SIG{HUP} = 'IGNORE';
348         $SIG{CHLD} = sub { $zombies++ };
349         
350         $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
351         $SIG{IO} = sub {        dbg('err', "SIGIO received"); };
352         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
353         $SIG{KILL} = 'DEFAULT';     # as if it matters....
354
355         # catch the rest with a hopeful message
356         for (keys %SIG) {
357                 if (!$SIG{$_}) {
358                         #               dbg('chan', "Catching SIG $_");
359                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
360                 }
361         }
362 }
363
364 # start dupe system
365 DXDupe::init();
366
367 # read in system messages
368 DXM->init();
369
370 # read in command aliases
371 CmdAlias->init();
372
373 # initialise the Geomagnetic data engine
374 Geomag->init();
375 WCY->init();
376
377 # initial the Spot stuff
378 Spot->init();
379
380 # initialise the protocol engine
381 dbg('err', "reading in duplicate spot and WWV info ...");
382 DXProt->init();
383
384 # put in a DXCluster node for us here so we can add users and take them away
385 DXNode->new($DXProt::me, $mycall, 0, 1, $DXProt::myprot_version); 
386
387 # read in any existing message headers and clean out old crap
388 dbg('err', "reading existing message headers ...");
389 DXMsg->init();
390 DXMsg::clean_old();
391
392 # read in any cron jobs
393 dbg('err', "reading cron jobs ...");
394 DXCron->init();
395
396 # read in database descriptors
397 dbg('err', "reading database descriptors ...");
398 DXDb::load();
399
400 # starting local stuff
401 dbg('err', "doing local initialisation ...");
402 eval {
403         Local::init();
404 };
405 dbg('local', "Local::init error $@") if $@;
406
407 # print various flags
408 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
409
410 # this, such as it is, is the main loop!
411 dbg('err', "orft we jolly well go ...");
412
413 #open(DB::OUT, "|tee /tmp/aa");
414
415 for (;;) {
416 #       $DB::trace = 1;
417         
418         Msg->event_loop(10, 0.001);
419         my $timenow = time;
420         process_inqueue();                      # read in lines from the input queue and despatch them
421 #       $DB::trace = 0;
422         
423         # do timed stuff, ongoing processing happens one a second
424         if ($timenow != $systime) {
425                 reap if $zombies;
426                 $systime = $timenow;
427                 DXCron::process();      # do cron jobs
428                 DXCommandmode::process(); # process ongoing command mode stuff
429                 DXProt::process();              # process ongoing ak1a pcxx stuff
430                 DXConnect::process();
431                 DXMsg::process();
432                 DXDb::process();
433                 DXUser::process();
434                 DXDupe::process();
435                 
436                 eval { 
437                         Local::process();       # do any localised processing
438                 };
439                 dbg('local', "Local::process error $@") if $@;
440         }
441         if ($decease) {
442                 last if --$decease <= 0;
443         }
444 }
445 cease(0);
446 exit(0);
447
448