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