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