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