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