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