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