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