1419e318e15d5e704045c1fd764201cf8faf0e7c
[spider.git] / perl / cluster.pl
1 #!/usr/bin/env perl
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 #
11 #
12
13 package main;
14
15 require 5.10.1;
16 use warnings;
17
18 # make sure that modules are searched in the order local then perl
19 BEGIN {
20         umask 002;
21
22         # root of directory tree for this system
23         $root = "/spider";
24         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
25
26         unshift @INC, "$root/perl";     # this IS the right way round!
27         unshift @INC, "$root/local";
28
29         # do some validation of the input
30         die "The directory $root doesn't exist, please RTFM" unless -d $root;
31         die "$root/local doesn't exist, please RTFM" unless -d "$root/local";
32         die "$root/local/DXVars.pm doesn't exist, please RTFM" unless -e "$root/local/DXVars.pm";
33
34         # create some directories
35         mkdir "$root/local_cmd", 02777 unless -d "$root/local_cmd";
36         mkdir "$root/local_data", 02777 unless -d "$root/local_data";
37
38         # try to create and lock a lockfile (this isn't atomic but
39         # should do for now
40         $lockfn = "$root/local_data/cluster.lck";       # lock file name
41         if (-w $lockfn) {
42                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
43                 my $pid = <CLLOCK>;
44                 if ($pid) {
45                         chomp $pid;
46                         if (kill 0, $pid) {
47                                 warn "Lockfile ($lockfn) and process $pid exist, another cluster running?\n";
48                                 exit 1;
49                         }
50                 }
51                 unlink $lockfn;
52                 close CLLOCK;
53         }
54         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
55         print CLLOCK "$$\n";
56         close CLLOCK;
57
58         $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
59         $systime = time;
60 }
61
62                         
63 use Mojo::IOLoop;
64
65 use DXVars;
66 use SysVar;
67
68 use Msg;
69 use IntMsg;
70 use Internet;
71 use Listeners;
72 use ExtMsg;
73 use AGWConnect;
74 use AGWMsg;
75 use DXDebug;
76 use DXLog;
77 use DXLogPrint;
78 use DXUtil;
79 use DXChannel;
80 use DXUser;
81 use DXM;
82 use DXCommandmode;
83 use DXProtVars;
84 use DXProtout;
85 use DXProt;
86 use DXMsg;
87 use DXCron;
88 use DXConnect;
89 use DXBearing;
90 use DXDb;
91 use DXHash;
92 use DXDupe;
93 use Script;
94 use Prefix;
95 use Spot;
96 use Bands;
97 use Keps;
98 use Minimuf;
99 use Sun;
100 use Geomag;
101 use CmdAlias;
102 use Filter;
103 use AnnTalk;
104 use BBS;
105 use WCY;
106 use BadWords;
107 use Timer;
108 use Route;
109 use Route::Node;
110 use Route::User;
111 use Editable;
112 use Mrtg;
113 use USDB;
114 use UDPMsg;
115 use QSL;
116 use DXXml;
117 use DXSql;
118 use IsoTime;
119 use BPQMsg;
120
121 use Data::Dumper;
122 use IO::File;
123 use Fcntl ':flock';
124 use POSIX ":sys_wait_h";
125 use Version;
126 use Web;
127
128 use Local;
129
130 package main;
131
132 use strict;
133 use vars qw(@inqueue $systime $starttime $lockfn @outstanding_connects
134                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr
135                         $clusterport $mycall $decease $is_win $routeroot $me $reqreg $bumpexisting
136                         $allowdxby $dbh $dsn $dbuser $dbpass $do_xml $systime_days $systime_daystart
137                         $can_encode $maxconnect_user $maxconnect_node $idle_interval $log_flush_interval
138                         $broadcast_debug 
139                    );
140
141 @inqueue = ();                                  # the main input queue, an array of hashes
142 $systime = 0;                                   # the time now (in seconds)
143 $starttime = 0;                 # the starting time of the cluster
144 @outstanding_connects = ();     # list of outstanding connects
145 @listeners = ();                                # list of listeners
146 $reqreg = 0;                                    # 1 = registration required, 2 = deregister people
147 $bumpexisting = 1;                              # 1 = allow new connection to disconnect old, 0 - don't allow it
148 $allowdxby = 0;                                 # 1 = allow "dx by <othercall>", 0 - don't allow it
149 $maxconnect_user = 3;                   # the maximum no of concurrent connections a user can have at a time
150 $maxconnect_node = 0;                   # Ditto but for nodes. In either case if a new incoming connection
151                                                                 # takes the no of references in the routing table above these numbers
152                                                                 # then the connection is refused. This only affects INCOMING connections.
153 $idle_interval = 0.500;         # the wait between invocations of the main idle loop processing.
154 $log_flush_interval = 2;                # interval to wait between log flushes
155
156 our $ending;                                    # signal that we are ending;
157 our $broadcast_debug;                   # allow broadcasting of debug info down "enhanced" user connections
158 our $clssecs;                                   # the amount of cpu time the DXSpider process have consumed
159 our $cldsecs;                                   # the amount of cpu time any child processes have consumed
160
161
162 # send a message to call on conn and disconnect
163 sub already_conn
164 {
165         my ($conn, $call, $mess) = @_;
166
167         $conn->disable_read(1);
168         dbg("-> D $call $mess\n") if isdbg('chan');
169         $conn->send_now("D$call|$mess");
170         sleep(2);
171         $conn->disconnect;
172 }
173
174 # handle incoming messages
175 sub new_channel
176 {
177         my ($conn, $msg) = @_;
178         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
179         return unless defined $sort;
180
181         unless (is_callsign($call)) {
182                 already_conn($conn, $call, DXM::msg($lang, "illcall", $call));
183                 return;
184         }
185
186         # set up the basic channel info
187         # is there one already connected to me - locally?
188         my $user = DXUser::get_current($call);
189         my $dxchan = DXChannel::get($call);
190         if ($dxchan) {
191                 if ($user && $user->is_node) {
192                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
193                         return;
194                 }
195                 if ($bumpexisting) {
196                         my $ip = $conn->peerhost || 'unknown';
197                         $dxchan->send_now('D', DXM::msg($lang, 'conbump', $call, $ip));
198                         LogDbg('DXCommand', "$call bumped off by $ip, disconnected");
199                         $dxchan->disconnect;
200                 } else {
201                         already_conn($conn, $call, DXM::msg($lang, 'conother', $call, $main::mycall));
202                         return;
203                 }
204         }
205
206         # (fairly) politely disconnect people that are connected to too many other places at once
207         my $r = Route::get($call);
208         if ($conn->{sort} && $conn->{sort} =~ /^I/ && $r && $user) {
209                 my @n = $r->parents;
210                 my $m = $r->isa('Route::Node') ? $maxconnect_node : $maxconnect_user;
211                 my $c = $user->maxconnect;
212                 my $v;
213                 $v = defined $c ? $c : $m;
214                 if ($v && @n >= $v) {
215                         my $nodes = join ',', @n;
216                         LogDbg('DXCommand', "$call has too many connections ($v) at $nodes - disconnected");
217                         already_conn($conn, $call, DXM::msg($lang, 'contomany', $call, $v, $nodes));
218                         return;
219                 }
220         }
221
222         # is he locked out ?
223         my $basecall = $call;
224         $basecall =~ s/-\d+$//;
225         my $baseuser = DXUser::get_current($basecall);
226         my $lock = $user->lockout if $user;
227         if ($baseuser && $baseuser->lockout || $lock) {
228                 if (!$user || !defined $lock || $lock) {
229                         my $host = $conn->peerhost || "unknown";
230                         LogDbg('DXCommand', "$call on $host is locked out, disconnected");
231                         $conn->disconnect;
232                         return;
233                 }
234         }
235
236         if ($user) {
237                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
238         } else {
239                 $user = DXUser->new($call);
240         }
241
242         # create the channel
243         if ($user->is_node) {
244                 $dxchan = DXProt->new($call, $conn, $user);
245         } elsif ($user->is_user) {
246                 $dxchan = DXCommandmode->new($call, $conn, $user);
247 #       } elsif ($user->is_bbs) {                                  # there is no support so
248 #               $dxchan = BBS->new($call, $conn, $user);               # don't allow it!!!
249         } else {
250                 die "Invalid sort of user on $call = $sort";
251         }
252
253         # check that the conn has a callsign
254         $conn->conns($call) if $conn->isa('IntMsg');
255
256         # set callbacks
257         $conn->set_error(sub {my $err = shift; LogDbg('DXCommand', "Comms error '$err' received for call $dxchan->{call}"); $dxchan->disconnect(1);});
258         $conn->set_on_eof(sub {$dxchan->disconnect});
259         $conn->set_rproc(sub {my ($conn,$msg) = @_; $dxchan->rec($msg);});
260         $dxchan->rec($msg);
261 }
262
263
264 sub login
265 {
266         return \&new_channel;
267 }
268
269 our $ceasing;
270
271 # cease running this program, close down all the connections nicely
272 sub cease
273 {
274         my $dxchan;
275
276         cluck("ceasing") if $ceasing; 
277         
278         return if $ceasing++;
279         
280         unless ($is_win) {
281                 $SIG{'TERM'} = 'IGNORE';
282                 $SIG{'INT'} = 'IGNORE';
283         }
284
285         DXUser::sync;
286
287         if (defined &Local::finish) {
288                 eval {
289                         Local::finish();   # end local processing
290                 };
291                 dbg("Local::finish error $@") if $@;
292         }
293
294
295         # disconnect AGW
296         AGWMsg::finish();
297         BPQMsg::finish();
298
299         # disconnect UDP customers
300         UDPMsg::finish();
301
302         # end everything else
303         DXUser::finish();
304         DXDupe::finish();
305
306         # close all databases
307         DXDb::closeall;
308
309         # close all listeners
310         foreach my $l (@listeners) {
311                 $l->close_server;
312         }
313
314         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) ended");
315         dbg("bye bye everyone - bye bye");
316         dbgclose();
317         Logclose();
318
319         $dbh->finish if $dbh;
320
321         unlink $lockfn;
322 }
323
324 # the reaper of children
325 sub reap
326 {
327         my $cpid;
328         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
329                 dbg("cpid: $cpid") if isdbg('reap');
330 #               Msg->pid_gone($cpid);
331                 $zombies-- if $zombies > 0;
332         }
333         dbg("cpid: $cpid") if isdbg('reap');
334 }
335
336 # this is where the input queue is dealt with and things are dispatched off to other parts of
337 # the cluster
338
339 sub uptime
340 {
341         my $t = $systime - $starttime;
342         my $days = int $t / 86400;
343         $t -= $days * 86400;
344         my $hours = int $t / 3600;
345         $t -= $hours * 3600;
346         my $mins = int $t / 60;
347         return sprintf "%d %02d:%02d", $days, $hours, $mins;
348 }
349
350 sub AGWrestart
351 {
352         AGWMsg::init(\&new_channel);
353 }
354
355 our $io_disconnected;
356
357 sub idle_loop
358 {
359         my $timenow = time;
360
361         BPQMsg::process();
362 #       DXChannel::process();
363
364         #      $DB::trace = 0;
365
366         # do timed stuff, ongoing processing happens one a second
367         if ($timenow != $systime) {
368                 reap() if $zombies;
369                 $systime = $timenow;
370                 my $days = int ($systime / 86400);
371                 if ($systime_days != $days) {
372                         $systime_days = $days;
373                         $systime_daystart = $days * 86400;
374                 }
375                 IsoTime::update($systime);
376                 DXCron::process();      # do cron jobs
377                 DXCommandmode::process(); # process ongoing command mode stuff
378                 DXXml::process();
379                 DXProt::process();              # process ongoing ak1a pcxx stuff
380                 DXConnect::process();
381                 DXMsg::process();
382                 DXDb::process();
383                 DXUser::process();
384                 DXDupe::process();
385                 DXCron::process();                      # do cron jobs
386                 IsoTime::update($systime);
387                 DXProt::process();                      # process ongoing ak1a pcxx stuff
388                 DXConnect::process();
389                 DXUser::process();
390                 AGWMsg::process();
391                 
392                 Timer::handler();
393                 DXLog::flushall();
394         }
395
396         if (defined &Local::process) {
397                 eval {
398                         Local::process();       # do any localised processing
399                 };
400                 dbg("Local::process error $@") if $@;
401         }
402
403         while ($ending) {
404                 my $dxchan;
405
406                 dbg("DXSpider Ending $ending");
407
408                 unless ($io_disconnected++) {
409
410                         # disconnect users
411                         foreach $dxchan (DXChannel::get_all_users) {
412                                 $dxchan->disconnect;
413                         }
414
415                         # disconnect nodes
416                         foreach $dxchan (DXChannel::get_all_nodes) {
417                                 next if $dxchan == $main::me;
418                                 $dxchan->disconnect(2);
419                         }
420                         $main::me->disconnect;
421                 }
422
423                 Mojo::IOLoop->stop if --$ending <= 0;
424         }
425 }
426
427 sub setup_start
428 {
429
430         #############################################################
431         #
432         # The start of the main line of code
433         #
434         #############################################################
435
436         $starttime = $systime = time;
437         $systime_days = int ($systime / 86400);
438         $systime_daystart = $systime_days * 86400;
439         $lang = 'en' unless $lang;
440
441         unless ($DB::VERSION) {
442                 $SIG{INT} = $SIG{TERM} = \&cease;
443         }
444
445         # open the debug file, set various FHs to be unbuffered
446         dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
447         foreach (@debug) {
448                 dbgadd($_);
449         }
450         STDOUT->autoflush(1);
451
452         
453         # try to load the database
454         if (DXSql::init($dsn)) {
455                 $dbh = DXSql->new($dsn);
456                 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
457         }
458
459         # try to load Encode and Git
460         {
461                 local $^W = 0;
462                 my $w = $SIG{__DIE__};
463                 $SIG{__DIE__} = 'IGNORE';
464                 eval { require Encode; };
465                 unless ($@) {
466                         import Encode;
467                         $can_encode = 1;
468                 }
469                 eval { require Git; };
470                 unless ($@) {
471                         import Git;
472                 
473                         # determine the real version number
474                         my $repo = Git->repository(Directory => "$root/.git");
475                         if ($repo) {
476                                 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
477                                 if ($desc) {
478                                         my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
479                                         $version = $v;
480                                         $build = $b || 0;
481                                         $gitversion = "$g\[r]";
482                                 }
483                         }
484                 }
485                 $SIG{__DIE__} = $w;
486         }
487
488         # try to load XML::Simple
489         DXXml::init();
490
491         # banner
492         my ($year) = (gmtime)[5];
493         $year += 1900;
494         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
495         dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
496
497         # load Prefixes
498         dbg("loading prefixes ...");
499         dbg(USDB::init());
500         my $r = Prefix::init();
501         confess $r if $r;
502
503         # load band data
504         dbg("loading band data ...");
505         Bands::load();
506
507         # initialise User file system
508         dbg("loading user file system ...");
509         DXUser::init(1);
510
511         # look for the sysop and the alias user and complain if they aren't there
512         {
513                 die "\$myalias \& \$mycall are the same ($mycall)!, they must be different (hint: make \$mycall = '${mycall}-2';). Oh and don't forget to rerun create_sysop.pl!" if $mycall eq $myalias;
514                 my $ref = DXUser::get($mycall);
515                 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
516                 my $oldsort = $ref->sort;
517                 if ($oldsort ne 'S') {
518                         $ref->sort('S');
519                         dbg "Resetting node type from $oldsort -> DXSpider ('S')";
520                 }
521                 $ref = DXUser::get($myalias);
522                 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
523                 $oldsort = $ref->sort;
524                 if ($oldsort ne 'U') {
525                         $ref->sort('U');
526                         dbg "Resetting sysop user type from $oldsort -> User ('U')";
527                 }
528         }
529
530         # start listening for incoming messages/connects
531         dbg("starting listeners ...");
532         my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
533         $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
534         push @listeners, $conn;
535         dbg("Internal port: $clusteraddr $clusterport using IntMsg");
536         foreach my $l (@main::listen) {
537                 no strict 'refs';
538                 my $pkg = $l->[2] || 'ExtMsg';
539                 my $login = $l->[3] || 'login';
540
541                 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
542                 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
543                 push @listeners, $conn;
544                 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
545         }
546
547         dbg("AGW Listener") if $AGWMsg::enable;
548         AGWrestart();
549
550         dbg("BPQ Listener") if $BPQMsg::enable;
551         BPQMsg::init(\&new_channel);
552
553         dbg("UDP Listener") if $UDPMsg::enable;
554         UDPMsg::init(\&new_channel);
555
556         # load bad words
557         dbg("load badwords: " . (BadWords::load or "Ok"));
558
559         # prime some signals
560         unless ($DB::VERSION) {
561                 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
562         }
563
564         unless ($is_win) {
565                 $SIG{HUP} = 'IGNORE';
566                 $SIG{CHLD} = sub { $zombies++ };
567
568                 $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
569                 $SIG{IO} = sub {        dbg("SIGIO received"); };
570                 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
571                 $SIG{KILL} = 'DEFAULT'; # as if it matters....
572
573                 # catch the rest with a hopeful message
574                 for (keys %SIG) {
575                         if (!$SIG{$_}) {
576                                 #               dbg("Catching SIG $_") if isdbg('chan');
577                                 $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
578                         }
579                 }
580         }
581
582         # start dupe system
583         dbg("Starting Dupe system");
584         DXDupe::init();
585
586         # read in system messages
587         dbg("Read in Messages");
588         DXM->init();
589
590         # read in command aliases
591         dbg("Read in Aliases");
592         CmdAlias->init();
593
594         # initialise the Geomagnetic data engine
595         dbg("Start WWV");
596         Geomag->init();
597         dbg("Start WCY");
598         WCY->init();
599
600         # initial the Spot stuff
601         dbg("Starting DX Spot system");
602         Spot->init();
603
604         # initialise the protocol engine
605         dbg("Start Protocol Engines ...");
606         DXProt->init();
607
608         # put in a DXCluster node for us here so we can add users and take them away
609         $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
610         $routeroot->do_pc9x(1);
611         $routeroot->via_pc92(1);
612
613         # make sure that there is a routing OUTPUT node default file
614         #unless (Filter::read_in('route', 'node_default', 0)) {
615         #       my $dxcc = $main::me->dxcc;
616         #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
617         #}
618
619         # read in any existing message headers and clean out old crap
620         dbg("reading existing message headers ...");
621         DXMsg->init();
622         DXMsg::clean_old();
623
624         # read in any cron jobs
625         dbg("reading cron jobs ...");
626         DXCron->init();
627
628         # read in database desriptors
629         dbg("reading database descriptors ...");
630         DXDb::load();
631
632         # starting local stuff
633         dbg("doing local initialisation ...");
634         QSL::init(1);
635         if (defined &Local::init) {
636                 eval {
637                         Local::init();
638                 };
639                 dbg("Local::init error $@") if $@;
640         }
641
642
643         # this, such as it is, is the main loop!
644         dbg("orft we jolly well go ...");
645         my $script = new Script "startup";
646         $script->run($main::me) if $script;
647
648         #open(DB::OUT, "|tee /tmp/aa");
649 }
650
651
652 setup_start();
653
654 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
655 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
656 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
657
658 Web::start_node();
659
660 cease(0);
661 exit(0);
662