more mrtg, store in 10ths and display to 0.1 sec
[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
356 sub setup_start
357 {
358
359         #############################################################
360         #
361         # The start of the main line of code
362         #
363         #############################################################
364
365         $starttime = $systime = time;
366         $systime_days = int ($systime / 86400);
367         $systime_daystart = $systime_days * 86400;
368         $lang = 'en' unless $lang;
369
370         unless ($DB::VERSION) {
371                 $SIG{INT} = $SIG{TERM} = \&cease;
372         }
373
374         # open the debug file, set various FHs to be unbuffered
375         dbginit($broadcast_debug ? \&DXCommandmode::broadcast_debug : undef);
376         foreach (@debug) {
377                 dbgadd($_);
378         }
379         STDOUT->autoflush(1);
380
381         
382         # try to load the database
383         if (DXSql::init($dsn)) {
384                 $dbh = DXSql->new($dsn);
385                 $dbh = $dbh->connect($dsn, $dbuser, $dbpass) if $dbh;
386         }
387
388         # try to load Encode and Git
389         {
390                 local $^W = 0;
391                 my $w = $SIG{__DIE__};
392                 $SIG{__DIE__} = 'IGNORE';
393                 eval { require Encode; };
394                 unless ($@) {
395                         import Encode;
396                         $can_encode = 1;
397                 }
398                 eval { require Git; };
399                 unless ($@) {
400                         import Git;
401                 
402                         # determine the real version number
403                         my $repo = Git->repository(Directory => "$root/.git");
404                         if ($repo) {
405                                 my $desc = $repo->command_oneline(['describe', '--long'], STDERR => 0);
406                                 if ($desc) {
407                                         my ($v, $s, $b, $g) = $desc =~ /^([\d.]+)(?:\.(\d+))?-(\d+)-g([0-9a-f]+)/;
408                                         $version = $v;
409                                         $build = $b || 0;
410                                         $gitversion = "$g\[r]";
411                                 }
412                         }
413                 }
414                 $SIG{__DIE__} = $w;
415         }
416
417         # try to load XML::Simple
418         DXXml::init();
419
420         # banner
421         my ($year) = (gmtime)[5];
422         $year += 1900;
423         LogDbg('cluster', "DXSpider V$version, build $build (git: $gitversion) started");
424         dbg("Copyright (c) 1998-$year Dirk Koopman G1TLH");
425
426         # load Prefixes
427         dbg("loading prefixes ...");
428         dbg(USDB::init());
429         my $r = Prefix::init();
430         confess $r if $r;
431
432         # load band data
433         dbg("loading band data ...");
434         Bands::load();
435
436         # initialise User file system
437         dbg("loading user file system ...");
438         DXUser::init(1);
439
440         # look for the sysop and the alias user and complain if they aren't there
441         {
442                 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;
443                 my $ref = DXUser::get($mycall);
444                 die "$mycall missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
445                 my $oldsort = $ref->sort;
446                 if ($oldsort ne 'S') {
447                         $ref->sort('S');
448                         dbg "Resetting node type from $oldsort -> DXSpider ('S')";
449                 }
450                 $ref = DXUser::get($myalias);
451                 die "$myalias missing, run the create_sysop.pl script and please RTFM" unless $ref && $ref->priv == 9;
452                 $oldsort = $ref->sort;
453                 if ($oldsort ne 'U') {
454                         $ref->sort('U');
455                         dbg "Resetting sysop user type from $oldsort -> User ('U')";
456                 }
457         }
458
459         # start listening for incoming messages/connects
460         dbg("starting listeners ...");
461         my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
462         $conn->conns("Server $clusteraddr/$clusterport using IntMsg");
463         push @listeners, $conn;
464         dbg("Internal port: $clusteraddr $clusterport using IntMsg");
465         foreach my $l (@main::listen) {
466                 no strict 'refs';
467                 my $pkg = $l->[2] || 'ExtMsg';
468                 my $login = $l->[3] || 'login';
469
470                 $conn = $pkg->new_server($l->[0], $l->[1], \&{"${pkg}::${login}"});
471                 $conn->conns("Server $l->[0]/$l->[1] using ${pkg}::${login}");
472                 push @listeners, $conn;
473                 dbg("External Port: $l->[0] $l->[1] using ${pkg}::${login}");
474         }
475
476         dbg("AGW Listener") if $AGWMsg::enable;
477         AGWrestart();
478
479         dbg("BPQ Listener") if $BPQMsg::enable;
480         BPQMsg::init(\&new_channel);
481
482         dbg("UDP Listener") if $UDPMsg::enable;
483         UDPMsg::init(\&new_channel);
484
485         # load bad words
486         dbg("load badwords: " . (BadWords::load or "Ok"));
487
488         # prime some signals
489         unless ($DB::VERSION) {
490                 $SIG{INT} = $SIG{TERM} = sub { $ending = 10; };
491         }
492
493         unless ($is_win) {
494                 $SIG{HUP} = 'IGNORE';
495                 $SIG{CHLD} = sub { $zombies++ };
496
497                 $SIG{PIPE} = sub {      dbg("Broken PIPE signal received"); };
498                 $SIG{IO} = sub {        dbg("SIGIO received"); };
499                 $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
500                 $SIG{KILL} = 'DEFAULT'; # as if it matters....
501
502                 # catch the rest with a hopeful message
503                 for (keys %SIG) {
504                         if (!$SIG{$_}) {
505                                 #               dbg("Catching SIG $_") if isdbg('chan');
506                                 $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  };
507                         }
508                 }
509         }
510
511         # start dupe system
512         dbg("Starting Dupe system");
513         DXDupe::init();
514
515         # read in system messages
516         dbg("Read in Messages");
517         DXM->init();
518
519         # read in command aliases
520         dbg("Read in Aliases");
521         CmdAlias->init();
522
523         # initialise the Geomagnetic data engine
524         dbg("Start WWV");
525         Geomag->init();
526         dbg("Start WCY");
527         WCY->init();
528
529         # initial the Spot stuff
530         dbg("Starting DX Spot system");
531         Spot->init();
532
533         # initialise the protocol engine
534         dbg("Start Protocol Engines ...");
535         DXProt->init();
536
537         # put in a DXCluster node for us here so we can add users and take them away
538         $routeroot = Route::Node->new($mycall, $version*100+5300, Route::here($main::me->here)|Route::conf($main::me->conf));
539         $routeroot->do_pc9x(1);
540         $routeroot->via_pc92(1);
541
542         # make sure that there is a routing OUTPUT node default file
543         #unless (Filter::read_in('route', 'node_default', 0)) {
544         #       my $dxcc = $main::me->dxcc;
545         #       $Route::filterdef->cmd($main::me, 'route', 'accept', "node_default call $mycall" );
546         #}
547
548         # read in any existing message headers and clean out old crap
549         dbg("reading existing message headers ...");
550         DXMsg->init();
551         DXMsg::clean_old();
552
553         # read in any cron jobs
554         dbg("reading cron jobs ...");
555         DXCron->init();
556
557         # read in database desriptors
558         dbg("reading database descriptors ...");
559         DXDb::load();
560
561         # starting local stuff
562         dbg("doing local initialisation ...");
563         QSL::init(1);
564         if (defined &Local::init) {
565                 eval {
566                         Local::init();
567                 };
568                 dbg("Local::init error $@") if $@;
569         }
570
571
572         # this, such as it is, is the main loop!
573         dbg("orft we jolly well go ...");
574         my $script = new Script "startup";
575         $script->run($main::me) if $script;
576
577         #open(DB::OUT, "|tee /tmp/aa");
578 }
579
580 our $io_disconnected;
581
582 sub idle_loop
583 {
584         BPQMsg::process();
585
586         if (defined &Local::process) {
587                 eval {
588                         Local::process();       # do any localised processing
589                 };
590                 dbg("Local::process error $@") if $@;
591         }
592
593         while ($ending) {
594                 my $dxchan;
595
596                 dbg("DXSpider Ending $ending");
597
598                 unless ($io_disconnected++) {
599
600                         # disconnect users
601                         foreach $dxchan (DXChannel::get_all_users) {
602                                 $dxchan->disconnect;
603                         }
604
605                         # disconnect nodes
606                         foreach $dxchan (DXChannel::get_all_nodes) {
607                                 next if $dxchan == $main::me;
608                                 $dxchan->disconnect(2);
609                         }
610                         $main::me->disconnect;
611                 }
612
613                 Mojo::IOLoop->stop if --$ending <= 0;
614         }
615 }
616
617 sub per_sec
618 {
619         my $timenow = time;
620
621         reap() if $zombies;
622         $systime = $timenow;
623         my $days = int ($systime / 86400);
624         if ($systime_days != $days) {
625                 $systime_days = $days;
626                 $systime_daystart = $days * 86400;
627         }
628         IsoTime::update($systime);
629         DXCron::process();      # do cron jobs
630         DXCommandmode::process(); # process ongoing command mode stuff
631         DXXml::process();
632         DXProt::process();              # process ongoing ak1a pcxx stuff
633         DXConnect::process();
634         DXMsg::process();
635         DXDb::process();
636         DXUser::process();
637         DXDupe::process();
638         DXCron::process();                      # do cron jobs
639         IsoTime::update($systime);
640         DXProt::process();                      # process ongoing ak1a pcxx stuff
641         DXConnect::process();
642         DXUser::process();
643         AGWMsg::process();
644         
645         Timer::handler();
646         DXLog::flushall();
647 }
648
649 sub per_10_sec
650 {
651
652 }
653
654
655 sub per_minute
656 {
657
658 }
659
660 sub per_10_minute
661 {
662
663 }
664
665 sub per_hour
666 {
667
668 }
669
670 sub per_day
671 {
672
673 }
674
675 setup_start();
676
677 my $main_loop = Mojo::IOLoop->recurring($idle_interval => \&idle_loop);
678 my $log_flush_loop = Mojo::IOLoop->recurring($log_flush_interval => \&DXLog::flushall);
679 my $cpusecs_loop = Mojo::IOLoop->recurring(5 => sub {my @t = times; $clssecs = $t[0]+$t[1]; $cldsecs = $t[2]+$t[3]});
680 my $persec =  Mojo::IOLoop->recurring(1 => \&per_sec);
681 my $per10sec =  Mojo::IOLoop->recurring(10 => \&per_10_sec);
682 my $permin =  Mojo::IOLoop->recurring(60 => \&per_minute);
683 my $per10min =  Mojo::IOLoop->recurring(600 => \&per_10_minute);
684 my $perhour =  Mojo::IOLoop->recurring(3600 => \&per_hour);
685 my $perday =  Mojo::IOLoop->recurring(86400 => \&per_day);
686
687 Web::start_node();
688
689 cease(0);
690 exit(0);
691